import axios from "axios";
import type { AxiosInstance } from "axios";
import type { TAxiosInterceptors, TAxiosConfig } from "./type";
import { ElLoading } from "element-plus";
import type { ILoadingInstance } from "element-plus/lib/el-loading/src/loading.type";

const DEFAULT_LOADING = true;
class TAxios {
  instance: AxiosInstance;
  interceptor?: TAxiosInterceptors;
  loading?: ILoadingInstance;
  showLoading: boolean;
  constructor(config: TAxiosConfig) {
    this.instance = axios.create(config);
    this.interceptor = config.interceptor;
    this.showLoading = config.showLoading ?? DEFAULT_LOADING;
    // 单个实例对象的拦截器
    this.instance.interceptors.request.use(
      this.interceptor?.requestInterceptor,
      this.interceptor?.requestInterceptorCatch
    );
    this.instance.interceptors.response.use(
      this.interceptor?.responseInterceptor,
      this.interceptor?.responseInterceptorCatch
    );
    // 添加所有的实例都有的拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading === true) {
          this.loading = ElLoading.service({
            lock: true,
            text: "🚀正在攻克服务器....",
            background: "rgba(0,0,0,0.5)",
          });
        }
        return config;
      },
      (err) => {
        this.loading?.close();
        return err;
      }
    ),
      this.instance.interceptors.response.use(
        (res) => {
          this.loading?.close();
          const data = res.data;
          return data;
        },
        (err) => {
          this.loading?.close();
          return err;
        }
      );
  }
  request<T>(config: TAxiosConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.interceptor?.requestInterceptor) {
        config = config.interceptor.requestInterceptor(config);
      }
      if (config.showLoading === false) {
        this.showLoading = config.showLoading;
      }
      this.instance
        .request<any, T>(config)
        .then((res) => {
          if (config.interceptor?.responseInterceptor) {
            res = config.interceptor.responseInterceptor(res);
          }
          this.showLoading = DEFAULT_LOADING;
          resolve(res);
        })
        .catch((err) => {
          this.showLoading = DEFAULT_LOADING;
          reject(err);
          return err;
        });
    });
  }
  get<T>(config: TAxiosConfig): Promise<T> {
    return this.request<T>({ ...config, method: "GET" });
  }

  post<T>(config: TAxiosConfig): Promise<T> {
    return this.request<T>({ ...config, method: "POST" });
  }

  delete<T>(config: TAxiosConfig): Promise<T> {
    return this.request<T>({ ...config, method: "DELETE" });
  }

  patch<T>(config: TAxiosConfig): Promise<T> {
    return this.request<T>({ ...config, method: "PATCH" });
  }
}

export default TAxios;
